
const {User,TestPaper,QuestionBase,Question,TestQuestion,Sequelize} = require('../model/dbModel')

/**
 * 获取试卷列表
 * @description
 * @author D31
 * @param {Number} page 页码
 * @param {Number} pageSize 页面大小
 * @param {String} username 用户名
 * @return {Promise<{status}|Model[]|{msg: string, status: number}|{msg: string, data: Model[] | {msg: string, status: number}, status: number}|{msg: string, status: number}>}
 */
async function testPaperList(page, pageSize, username) {
    if (!page || page < 1 || !pageSize || pageSize < 1) return {
        status: 2,
        msg: "请输入正确的页码和页面大小"
    }
    let user = await User.findOne({
        where: {
            username: username
        }
    })
    if (!user) return {
        status: 11,
        msg: "用户不存在"
    }
    let offset = (page - 1) * pageSize;
    let result = await TestPaper.findAll({
            offset: offset,
            limit: pageSize * 1, //隐式转换
            raw: true,
            where: {
                creator_id: user.id
            },
            attributes: [
                ['id', 'tp_id'],
                'tp_name',
                'tp_description',
                'createdAt'
            ]
        }).catch(function(e) {
            console.error(e)
            return {
                status: 50,
                msg: "数据库出现了未知错误"
            }
        })
        //console.log(result)
    if (result.status) return result;
    else return {
        data: result,
        status: 0,
        msg: "查询成功"
    };
}

/**
 * 创建试卷
 * @param {string} name 试卷的名字
 * @param {string} description 试卷的介绍或者是说明
 * @param {string} username 用户名
 * @return {Promise<void>}
 */
async function createTestPaper(name, description, username) {

    let user = await User.findOne({
        where: {
            username: username
        }
    })
    if (!user) return {
        status: 11,
        msg: "用户不存在"
    }
    if (user.userrole !== "teacher") return {
            status: 12,
            msg: "对不起该用户无权限创建试卷"
        }
        //新建试卷
    let tp = await TestPaper.create({
        tp_name: name,
        tp_description: description,
        creator_id: user.id,
    })
    return {
        status: 0,
        msg: "创建成功"
    }

}
/**
 * 删除试卷
 * @param {Number} tp_id 试卷id
 * @param {String} username 用户名
 * @return {Promise<{msg: string, status: number}>}
 */
async function deleteTestPaper(tp_id, username) {
    let user = await User.findOne({
        where: {
            username: username
        }
    })
    if (!user) return {
        status: 11,
        msg: "用户不存在"
    }
    if (user.userrole !== "teacher") return {
        status: 12,
        msg: "对不起该用户无权限删除试卷"
    }

    let num = await TestPaper.destroy({
        where: {
            id: tp_id,
            creator_id: user.id
        }
    }).catch(e => {
        console.log(e)
    })
    if (num === 0) {
        return {
            status: 1,
            msg: "权限不足或试卷不存在或者删除失败"
        }
    }
    return {
        status: 0,
        msg: "试卷删除成功",
        deleteNum: num,

    }
}

/**
 * 向试卷添加试题
 * @param {String} tp_id 试卷的ID
 * @param {Number[]} question_ids 要添加的题目ID
 * @param {String}username 用户名
 * @return {Promise<void>}
 */
async function addTestQuestion(tp_id, question_ids, username) {
    //判断用户的合法性
    let user = await User.findOne({
        where: {
            username: username
        }
    })
    if (!user) return {
            status: 11,
            msg: "用户不存在"
        }
        //检测用户对试卷权限
    let tp = await TestPaper.findOne({
        where: {
            creator_id: user.id,
            id: tp_id
        }
    })
    if (!tp) {
        return {
            status: 12,
            msg: "用户权限不足或试卷不存在"
        }
    }
    //检测用户对问题的权限及问题的存在性
    let qts = [];
    for (let i = 0; i < question_ids.length; i++) {
        let qt = await Question.findOne({
            where: {
                id: question_ids[i],
                creatorid: user.id
            }
        })
        if (!qt) return {
            status: 12,
            msg: "用户权限不足或问题不存在"
        }
        else qts.push(qt)
    }
    //向试卷插入试题
    let a = await tp.addQuestions(question_ids);
    return {
        addNum: a.length,
        status: 0,
        msg: "添加试题成功"
    }


}

/**
 * 向试卷移除试题
 * @param {String} tp_id 试卷的ID
 * @param {Number[]} question_ids 要移除的题目ID
 * @param {String}username 用户名
 * @return {Promise<void>}
 */
async function removeTestQuestion(tp_id, question_ids, username) {
    //判断用户的合法性
    let user = await User.findOne({
        where: {
            username: username
        }
    })
    if (!user) return {
            status: 11,
            msg: "用户不存在"
        }
        //检测用户对试卷权限
    let tp = await TestPaper.findOne({
        where: {
            id: tp_id,
            creator_id: user.id
        }
    })
    if (!tp) return {
            status: 1,
            msg: "无此试卷操作权限或试卷不存在",
        }
        //移除试题
    for (let i = 0; i < question_ids.length; i++) {
        let tq = await TestQuestion.destroy({
            where: {
                test_paper_id: tp_id,
                question_id: question_ids[i]
            }
        }).catch(e => {
            return {
                status: 50,
                msg: "服务产生了不知名的错误"
            }
        })
        if (!tq) return {
            status: 12,
            msg: "用户权限不足或试题存在异常"
        }
    }
    return {
        status: 0,
        msg: "试题已删除"
    }


}

/**
 * 获取试卷的详情(包含试题)
 * @param {Number} tp_id
 * @param {String} username
 * @return {Promise<void>}
 */
async function testPaperDetail(tp_id, username) {
    let user = await User.findOne({
        where:{
            username:username
        }
    })
    if(!user) return{
        status:11,
        msg:"用户不存在"
    }
    //检测用户对试卷权限
    let tp = await TestPaper.findOne({
        where:{
            id:tp_id,
            creator_id:user.id
        }
    })
    if(!tp)return{
        status:1,
        msg:"无此试卷操作权限或试卷不存在",
    }
    let tpdetail  = await TestPaper.findAll({
        where:{
            id:tp_id
        },
        attributes:[
            'id',
            'tp_name',
            'tp_description',
        ],
        include:[
            {
            model:User,
            attributes:['username','usernickname']
            },
            {
                model:Question,
                attributes:[
                    'id',
                    'title',
                    'type',
                    'analysis',
                    'difficulty',
                    'qt_body',
                    'QBID',
                ],
                through:{
                    model:TestQuestion,
                    attributes:[]
                },
                include:{
                    model:User,
                    attributes:['username','usernickname']
                },
            }

        ],
        //使问题类型按升序排序
        order:[
            [Question,'type']
        ],
    })

    return {
        status:0,
        msg:"试卷详情查询成功",
        data:tpdetail,
    }
}

module.exports = {
    testPaperList,
    createTestPaper,
    deleteTestPaper,
    addTestQuestion,
    removeTestQuestion,
    testPaperDetail,
}